import sys

from django.core.cache import cache
from django.http import JsonResponse

from .exception import BizError

from django.utils.deprecation import MiddlewareMixin


class AuthMiddleware(MiddlewareMixin):

    def process_request(self, request):
        path_str = request.path
        # 判断是否需要路径中是否包含auth字符，包含则需要登录验证后使用
        if path_str.find('/api/auth') < 0:
            return None

        auth_token = request.META.get('HTTP_AUTH_TOKEN')
        exist_flag = cache.has_key(auth_token)
        if auth_token is None or not exist_flag:
            res = {
                'code': 1001,
                'msg': '请先登录'
            }
            return JsonResponse(res)
        return None

    def process_exception(self, request, exception):
        path_str = request.path
        # 只处理api接口中的异常，和返回视图的函数区分开
        if path_str.find('/api') < 0:
            return None

        if isinstance(exception, BizError):
            print(sys.exc_info())
            res = {
                "code": exception.err_code,
                "msg": exception.err_msg,
            }
        else:
            print(exception)
            res = {
                "code": 500,
                "msg": '服务器错误',
            }
        return JsonResponse(res)
